Skills Network Logo

Extracting and Visualizing Stock Data

Description

Extracting essential data from a dataset and displaying it is a necessary part of data science; therefore individuals can make correct decisions based on the data. In this assignment, you will extract some stock data, you will then display this data in a graph.

Table of Contents

  • Define a Function that Makes a Graph
  • Question 1: Use yfinance to Extract Stock Data
  • Question 2: Use Webscraping to Extract Tesla Revenue Data
  • Question 3: Use yfinance to Extract Stock Data
  • Question 4: Use Webscraping to Extract GME Revenue Data
  • Question 5: Plot Tesla Stock Graph
  • Question 6: Plot GameStop Stock Graph

Estimated Time Needed: 30 min


Note:- If you are working Locally using anaconda, please uncomment the following code and execute it. Use the version as per your python version.

In [1]:
!pip install yfinance
!pip install bs4
!pip install nbformat
!pip install --upgrade plotly
Collecting yfinance
  Downloading yfinance-0.2.54-py2.py3-none-any.whl.metadata (5.8 kB)
Collecting pandas>=1.3.0 (from yfinance)
  Downloading pandas-2.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (89 kB)
Collecting numpy>=1.16.5 (from yfinance)
  Downloading numpy-2.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (62 kB)
Requirement already satisfied: requests>=2.31 in /opt/conda/lib/python3.12/site-packages (from yfinance) (2.32.3)
Collecting multitasking>=0.0.7 (from yfinance)
  Downloading multitasking-0.0.11-py3-none-any.whl.metadata (5.5 kB)
Requirement already satisfied: platformdirs>=2.0.0 in /opt/conda/lib/python3.12/site-packages (from yfinance) (4.3.6)
Requirement already satisfied: pytz>=2022.5 in /opt/conda/lib/python3.12/site-packages (from yfinance) (2024.2)
Requirement already satisfied: frozendict>=2.3.4 in /opt/conda/lib/python3.12/site-packages (from yfinance) (2.4.6)
Collecting peewee>=3.16.2 (from yfinance)
  Downloading peewee-3.17.9.tar.gz (3.0 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.0/3.0 MB 101.1 MB/s eta 0:00:00
  Installing build dependencies ... one
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Requirement already satisfied: beautifulsoup4>=4.11.1 in /opt/conda/lib/python3.12/site-packages (from yfinance) (4.12.3)
Requirement already satisfied: soupsieve>1.2 in /opt/conda/lib/python3.12/site-packages (from beautifulsoup4>=4.11.1->yfinance) (2.5)
Requirement already satisfied: python-dateutil>=2.8.2 in /opt/conda/lib/python3.12/site-packages (from pandas>=1.3.0->yfinance) (2.9.0.post0)
Collecting tzdata>=2022.7 (from pandas>=1.3.0->yfinance)
  Downloading tzdata-2025.1-py2.py3-none-any.whl.metadata (1.4 kB)
Requirement already satisfied: charset_normalizer<4,>=2 in /opt/conda/lib/python3.12/site-packages (from requests>=2.31->yfinance) (3.4.1)
Requirement already satisfied: idna<4,>=2.5 in /opt/conda/lib/python3.12/site-packages (from requests>=2.31->yfinance) (3.10)
Requirement already satisfied: urllib3<3,>=1.21.1 in /opt/conda/lib/python3.12/site-packages (from requests>=2.31->yfinance) (2.3.0)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.12/site-packages (from requests>=2.31->yfinance) (2024.12.14)
Requirement already satisfied: six>=1.5 in /opt/conda/lib/python3.12/site-packages (from python-dateutil>=2.8.2->pandas>=1.3.0->yfinance) (1.17.0)
Downloading yfinance-0.2.54-py2.py3-none-any.whl (108 kB)
Downloading multitasking-0.0.11-py3-none-any.whl (8.5 kB)
Downloading numpy-2.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (16.1 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 16.1/16.1 MB 148.7 MB/s eta 0:00:00
Downloading pandas-2.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (12.7 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 12.7/12.7 MB 159.9 MB/s eta 0:00:00
Downloading tzdata-2025.1-py2.py3-none-any.whl (346 kB)
Building wheels for collected packages: peewee
  Building wheel for peewee (pyproject.toml) ... one
  Created wheel for peewee: filename=peewee-3.17.9-cp312-cp312-linux_x86_64.whl size=303802 sha256=175437a56f7e7286846310966bcf0f60b6b4422f384d74188036c9a342bcf0fb
  Stored in directory: /home/jupyterlab/.cache/pip/wheels/43/ef/2d/2c51d496bf084945ffdf838b4cc8767b8ba1cc20eb41588831
Successfully built peewee
Installing collected packages: peewee, multitasking, tzdata, numpy, pandas, yfinance
Successfully installed multitasking-0.0.11 numpy-2.2.3 pandas-2.2.3 peewee-3.17.9 tzdata-2025.1 yfinance-0.2.54
Collecting bs4
  Downloading bs4-0.0.2-py2.py3-none-any.whl.metadata (411 bytes)
Requirement already satisfied: beautifulsoup4 in /opt/conda/lib/python3.12/site-packages (from bs4) (4.12.3)
Requirement already satisfied: soupsieve>1.2 in /opt/conda/lib/python3.12/site-packages (from beautifulsoup4->bs4) (2.5)
Downloading bs4-0.0.2-py2.py3-none-any.whl (1.2 kB)
Installing collected packages: bs4
Successfully installed bs4-0.0.2
Requirement already satisfied: nbformat in /opt/conda/lib/python3.12/site-packages (5.10.4)
Requirement already satisfied: fastjsonschema>=2.15 in /opt/conda/lib/python3.12/site-packages (from nbformat) (2.21.1)
Requirement already satisfied: jsonschema>=2.6 in /opt/conda/lib/python3.12/site-packages (from nbformat) (4.23.0)
Requirement already satisfied: jupyter-core!=5.0.*,>=4.12 in /opt/conda/lib/python3.12/site-packages (from nbformat) (5.7.2)
Requirement already satisfied: traitlets>=5.1 in /opt/conda/lib/python3.12/site-packages (from nbformat) (5.14.3)
Requirement already satisfied: attrs>=22.2.0 in /opt/conda/lib/python3.12/site-packages (from jsonschema>=2.6->nbformat) (25.1.0)
Requirement already satisfied: jsonschema-specifications>=2023.03.6 in /opt/conda/lib/python3.12/site-packages (from jsonschema>=2.6->nbformat) (2024.10.1)
Requirement already satisfied: referencing>=0.28.4 in /opt/conda/lib/python3.12/site-packages (from jsonschema>=2.6->nbformat) (0.36.2)
Requirement already satisfied: rpds-py>=0.7.1 in /opt/conda/lib/python3.12/site-packages (from jsonschema>=2.6->nbformat) (0.22.3)
Requirement already satisfied: platformdirs>=2.5 in /opt/conda/lib/python3.12/site-packages (from jupyter-core!=5.0.*,>=4.12->nbformat) (4.3.6)
Requirement already satisfied: typing-extensions>=4.4.0 in /opt/conda/lib/python3.12/site-packages (from referencing>=0.28.4->jsonschema>=2.6->nbformat) (4.12.2)
Requirement already satisfied: plotly in /opt/conda/lib/python3.12/site-packages (5.24.1)
Collecting plotly
  Downloading plotly-6.0.0-py3-none-any.whl.metadata (5.6 kB)
Collecting narwhals>=1.15.1 (from plotly)
  Downloading narwhals-1.29.1-py3-none-any.whl.metadata (10 kB)
Requirement already satisfied: packaging in /opt/conda/lib/python3.12/site-packages (from plotly) (24.2)
Downloading plotly-6.0.0-py3-none-any.whl (14.8 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 14.8/14.8 MB 82.6 MB/s eta 0:00:00
Downloading narwhals-1.29.1-py3-none-any.whl (308 kB)
Installing collected packages: narwhals, plotly
  Attempting uninstall: plotly
    Found existing installation: plotly 5.24.1
    Uninstalling plotly-5.24.1:
      Successfully uninstalled plotly-5.24.1
Successfully installed narwhals-1.29.1 plotly-6.0.0
In [2]:
import yfinance as yf
import pandas as pd
import requests
from bs4 import BeautifulSoup
import plotly.graph_objects as go
from plotly.subplots import make_subplots
In [3]:
import plotly.io as pio
pio.renderers.default = "iframe"

In Python, you can ignore warnings using the warnings module. You can use the filterwarnings function to filter or ignore specific warning messages or categories.

In [4]:
import warnings
# Ignore all warnings
warnings.filterwarnings("ignore", category=FutureWarning)

Define Graphing Function¶

In this section, we define the function make_graph. You don't have to know how the function works, you should only care about the inputs. It takes a dataframe with stock data (dataframe must contain Date and Close columns), a dataframe with revenue data (dataframe must contain Date and Revenue columns), and the name of the stock.

In [5]:
def make_graph(stock_data, revenue_data, stock):
    fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=("Historical Share Price", "Historical Revenue"), vertical_spacing = .3)
    stock_data_specific = stock_data[stock_data.Date <= '2021-06-14']
    revenue_data_specific = revenue_data[revenue_data.Date <= '2021-04-30']
    fig.add_trace(go.Scatter(x=pd.to_datetime(stock_data_specific.Date, infer_datetime_format=True), y=stock_data_specific.Close.astype("float"), name="Share Price"), row=1, col=1)
    fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data_specific.Date, infer_datetime_format=True), y=revenue_data_specific.Revenue.astype("float"), name="Revenue"), row=2, col=1)
    fig.update_xaxes(title_text="Date", row=1, col=1)
    fig.update_xaxes(title_text="Date", row=2, col=1)
    fig.update_yaxes(title_text="Price ($US)", row=1, col=1)
    fig.update_yaxes(title_text="Revenue ($US Millions)", row=2, col=1)
    fig.update_layout(showlegend=False,
    height=900,
    title=stock,
    xaxis_rangeslider_visible=True)
    fig.show()
    from IPython.display import display, HTML
    fig_html = fig.to_html()
    display(HTML(fig_html))

Use the make_graph function that we’ve already defined. You’ll need to invoke it in questions 5 and 6 to display the graphs and create the dashboard.

Note: You don’t need to redefine the function for plotting graphs anywhere else in this notebook; just use the existing function.

Question 1: Use yfinance to Extract Stock Data¶

Using the Ticker function enter the ticker symbol of the stock we want to extract data on to create a ticker object. The stock is Tesla and its ticker symbol is TSLA.

In [6]:
import yfinance as yf
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots

# Create a ticker object for Tesla
tsla_ticker = yf.Ticker("TSLA")

# Get historical stock data
stock_data = tsla_ticker.history(period="5y")

# Convert index to a column
stock_data.reset_index(inplace=True)
stock_data.rename(columns={"Date": "Date", "Close": "Close"}, inplace=True)

# Example revenue data (replace with actual revenue data)
revenue_data = pd.DataFrame({
    "Date": ["2021-03-31", "2021-06-30", "2021-09-30", "2021-12-31"],
    "Revenue": [10389, 11958, 13757, 17719]  # Replace with actual values
})

# Convert Date column to datetime
revenue_data["Date"] = pd.to_datetime(revenue_data["Date"])

# Call the function
make_graph(stock_data, revenue_data, "Tesla (TSLA)")
/tmp/ipykernel_477/109047474.py:5: UserWarning:

The argument 'infer_datetime_format' is deprecated and will be removed in a future version. A strict version of it is now the default, see https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. You can safely remove this argument.

/tmp/ipykernel_477/109047474.py:6: UserWarning:

The argument 'infer_datetime_format' is deprecated and will be removed in a future version. A strict version of it is now the default, see https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. You can safely remove this argument.

Using the ticker object and the function history extract stock information and save it in a dataframe named tesla_data. Set the period parameter to "max" so we get information for the maximum amount of time.

In [7]:
import yfinance as yf
import pandas as pd

# Create a ticker object for Tesla
tsla_ticker = yf.Ticker("TSLA")

# Extract historical stock data for the maximum period
tesla_data = tsla_ticker.history(period="max")

# Reset the index to convert the date into a column
tesla_data.reset_index(inplace=True)

# Display the first few rows
print(tesla_data.head())
                       Date      Open      High       Low     Close  \
0 2010-06-29 00:00:00-04:00  1.266667  1.666667  1.169333  1.592667   
1 2010-06-30 00:00:00-04:00  1.719333  2.028000  1.553333  1.588667   
2 2010-07-01 00:00:00-04:00  1.666667  1.728000  1.351333  1.464000   
3 2010-07-02 00:00:00-04:00  1.533333  1.540000  1.247333  1.280000   
4 2010-07-06 00:00:00-04:00  1.333333  1.333333  1.055333  1.074000   

      Volume  Dividends  Stock Splits  
0  281494500        0.0           0.0  
1  257806500        0.0           0.0  
2  123282000        0.0           0.0  
3   77097000        0.0           0.0  
4  103003500        0.0           0.0  

Reset the index using the reset_index(inplace=True) function on the tesla_data DataFrame and display the first five rows of the tesla_data dataframe using the head function. Take a screenshot of the results and code from the beginning of Question 1 to the results below.

In [8]:
tesla_data.reset_index(inplace=True)
tesla_data.head()
Out[8]:
index Date Open High Low Close Volume Dividends Stock Splits
0 0 2010-06-29 00:00:00-04:00 1.266667 1.666667 1.169333 1.592667 281494500 0.0 0.0
1 1 2010-06-30 00:00:00-04:00 1.719333 2.028000 1.553333 1.588667 257806500 0.0 0.0
2 2 2010-07-01 00:00:00-04:00 1.666667 1.728000 1.351333 1.464000 123282000 0.0 0.0
3 3 2010-07-02 00:00:00-04:00 1.533333 1.540000 1.247333 1.280000 77097000 0.0 0.0
4 4 2010-07-06 00:00:00-04:00 1.333333 1.333333 1.055333 1.074000 103003500 0.0 0.0

Question 2: Use Webscraping to Extract Tesla Revenue Data¶

Use the requests library to download the webpage https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/revenue.htm Save the text of the response as a variable named html_data.

In [9]:
import requests

# URL to download the webpage from
url = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/revenue.htm"

# Send a GET request to the URL
response = requests.get(url)

# Save the text of the response
html_data = response.text

# Optionally, print the first 500 characters of html_data to check
print(html_data[:500])
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<link rel="canonical" href="https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue" />
	

Parse the html data using beautiful_soup using parser i.e html5lib or html.parser.

In [15]:
from bs4 import BeautifulSoup

# Parse the HTML data using 'html.parser' or 'html5lib'
soup = BeautifulSoup(html_data, 'html.parser')  # or 'html5lib'

# Optionally, print the parsed HTML or a part of it
print(soup.prettify()[:500])  # Displaying the first 500 characters for review
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
 <!--<![endif]-->
 <head>
  <meta charset="utf-8"/>
  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"/>
  <link href="https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue" rel="canonical"/>
  <title>
   Te

Using BeautifulSoup or the read_html function extract the table with Tesla Revenue and store it into a dataframe named tesla_revenue. The dataframe should have columns Date and Revenue.

Step-by-step instructions

Here are the step-by-step instructions:

1. Create an Empty DataFrame
2. Find the Relevant Table
3. Check for the Tesla Quarterly Revenue Table
4. Iterate Through Rows in the Table Body
5. Extract Data from Columns
6. Append Data to the DataFrame

Click here if you need help locating the table
    
Below is the code to isolate the table, you will now need to loop through the rows and columns like in the previous lab
    
soup.find_all("tbody")[1]
    
If you want to use the read_html function the table is located at index 1

We are focusing on quarterly revenue in the lab.
In [18]:
pip install beautifulsoup
pip install html5lib
  Cell In[18], line 1
    pip install beautifulsoup
        ^
SyntaxError: invalid syntax

Execute the following line to remove the comma and dollar sign from the Revenue column.

In [ ]:
tesla_revenue["Revenue"] = tesla_revenue['Revenue'].str.replace(',|\$',"")

Execute the following lines to remove an null or empty strings in the Revenue column.

In [ ]:
tesla_revenue.dropna(inplace=True)

tesla_revenue = tesla_revenue[tesla_revenue['Revenue'] != ""]

Display the last 5 row of the tesla_revenue dataframe using the tail function. Take a screenshot of the results.

In [ ]:
tesla_revenue.tail()

Question 3: Use yfinance to Extract Stock Data¶

Using the Ticker function enter the ticker symbol of the stock we want to extract data on to create a ticker object. The stock is GameStop and its ticker symbol is GME.

In [19]:
import yfinance as yf

# Create a ticker object for GameStop (GME)
gme_ticker = yf.Ticker("GME")

# Optionally, print the information related to the ticker
print(gme_ticker.info)
{'address1': '625 Westport Parkway', 'city': 'Grapevine', 'state': 'TX', 'zip': '76051', 'country': 'United States', 'phone': '817 424 2000', 'website': 'https://www.gamestop.com', 'industry': 'Specialty Retail', 'industryKey': 'specialty-retail', 'industryDisp': 'Specialty Retail', 'sector': 'Consumer Cyclical', 'sectorKey': 'consumer-cyclical', 'sectorDisp': 'Consumer Cyclical', 'longBusinessSummary': 'GameStop Corp., a specialty retailer, provides games and entertainment products through its stores and ecommerce platforms in the United States, Canada, Australia, and Europe. The company sells new and pre-owned gaming platforms; accessories, such as controllers, gaming headsets, and virtual reality products; new and pre-owned gaming software; and in-game digital currency, digital downloadable content, and full-game downloads. It sells collectibles comprising apparel, toys, trading cards, gadgets, and other retail products for pop culture and technology enthusiasts, as well as engages in the digital asset wallet and NFT marketplace activities. The company operates stores and ecommerce sites under the GameStop, EB Games, and Micromania brands; and pop culture themed stores that sell collectibles, apparel, gadgets, electronics, toys, and other retail products under the Zing Pop Culture brand, as well as offers Game Informer magazine, a print and digital gaming publication. The company was formerly known as GSC Holdings Corp. GameStop Corp. was founded in 1996 and is headquartered in Grapevine, Texas.', 'fullTimeEmployees': 8000, 'companyOfficers': [{'maxAge': 1, 'name': 'Mr. Ryan  Cohen', 'age': 38, 'title': 'President, CEO & Executive Chairman', 'yearBorn': 1986, 'fiscalYear': 2023, 'exercisedValue': 0, 'unexercisedValue': 0}, {'maxAge': 1, 'name': 'Mr. Daniel William Moore', 'age': 41, 'title': 'Principal Accounting Officer & Principal Financial Officer', 'yearBorn': 1983, 'fiscalYear': 2023, 'totalPay': 277711, 'exercisedValue': 0, 'unexercisedValue': 0}, {'maxAge': 1, 'name': 'Mr. Mark Haymond Robinson', 'age': 46, 'title': 'General Counsel & Secretary', 'yearBorn': 1978, 'fiscalYear': 2023, 'totalPay': 337657, 'exercisedValue': 0, 'unexercisedValue': 0}], 'auditRisk': 7, 'boardRisk': 6, 'compensationRisk': 7, 'shareHolderRightsRisk': 3, 'overallRisk': 5, 'governanceEpochDate': 1740787200, 'compensationAsOfEpochDate': 1703980800, 'irWebsite': 'http://phx.corporate-ir.net/phoenix.zhtml?c=130125&p=irol-irhome', 'executiveTeam': [], 'maxAge': 86400, 'priceHint': 2, 'previousClose': 25.07, 'open': 24.74, 'dayLow': 24.05, 'dayHigh': 25.0068, 'regularMarketPreviousClose': 25.07, 'regularMarketOpen': 24.74, 'regularMarketDayLow': 24.05, 'regularMarketDayHigh': 25.0068, 'exDividendDate': 1552521600, 'payoutRatio': 0.0, 'fiveYearAvgDividendYield': 9.52, 'beta': -0.263, 'trailingPE': 121.0, 'forwardPE': -2420.0002, 'volume': 3247035, 'regularMarketVolume': 3247035, 'averageVolume': 7895756, 'averageVolume10days': 5102210, 'averageDailyVolume10Day': 5102210, 'bid': 24.19, 'ask': 24.27, 'bidSize': 12, 'askSize': 8, 'marketCap': 10812560384, 'fiftyTwoWeekLow': 9.95, 'fiftyTwoWeekHigh': 64.83, 'priceToSalesTrailing12Months': 2.4948223, 'fiftyDayAverage': 27.9264, 'twoHundredDayAverage': 25.08815, 'trailingAnnualDividendRate': 0.0, 'trailingAnnualDividendYield': 0.0, 'currency': 'USD', 'tradeable': False, 'enterpriseValue': 7048585216, 'profitMargins': 0.01456, 'floatShares': 408710634, 'sharesOutstanding': 446800000, 'sharesShort': 27717723, 'sharesShortPriorMonth': 32138831, 'sharesShortPreviousMonthDate': 1736899200, 'dateShortInterest': 1739491200, 'sharesPercentSharesOut': 0.062, 'heldPercentInsiders': 0.0849, 'heldPercentInstitutions': 0.32869998, 'shortRatio': 4.64, 'shortPercentOfFloat': 0.0744, 'impliedSharesOutstanding': 446800000, 'bookValue': 10.753, 'priceToBook': 2.2505348, 'lastFiscalYearEnd': 1706918400, 'nextFiscalYearEnd': 1738540800, 'mostRecentQuarter': 1730505600, 'netIncomeToCommon': 63100000, 'trailingEps': 0.2, 'forwardEps': -0.01, 'lastSplitFactor': '4:1', 'lastSplitDate': 1658448000, 'enterpriseToRevenue': 1.626, 'enterpriseToEbitda': 120.283, '52WeekChange': 0.6428572, 'SandP52WeekChange': 0.13287222, 'lastDividendValue': 0.095, 'lastDividendDate': 1552521600, 'quoteType': 'EQUITY', 'currentPrice': 24.2, 'targetHighPrice': 10.0, 'targetLowPrice': 10.0, 'targetMeanPrice': 10.0, 'targetMedianPrice': 10.0, 'recommendationKey': 'none', 'numberOfAnalystOpinions': 1, 'totalCash': 4616200192, 'totalCashPerShare': 10.332, 'ebitda': 58600000, 'totalDebt': 463500000, 'quickRatio': 4.25, 'currentRatio': 5.114, 'totalRevenue': 4334000128, 'debtToEquity': 9.647, 'revenuePerShare': 12.077, 'returnOnAssets': 0.00095, 'returnOnEquity': 0.0208, 'grossProfits': 1169699968, 'freeCashflow': -92362496, 'operatingCashflow': -27600000, 'revenueGrowth': -0.202, 'grossMargins': 0.26989, 'ebitdaMargins': 0.01352, 'operatingMargins': -0.02883, 'financialCurrency': 'USD', 'symbol': 'GME', 'language': 'en-US', 'region': 'US', 'typeDisp': 'Equity', 'quoteSourceName': 'Nasdaq Real Time Price', 'triggerable': True, 'customPriceAlertConfidence': 'HIGH', 'shortName': 'GameStop Corporation', 'longName': 'GameStop Corp.', 'regularMarketPrice': 24.2, 'regularMarketTime': 1741294802, 'exchange': 'NYQ', 'market': 'us_market', 'esgPopulated': False, 'regularMarketChangePercent': -3.47028, 'corporateActions': [], 'postMarketTime': 1741307656, 'marketState': 'POST', 'messageBoardId': 'finmb_1342560', 'exchangeTimezoneName': 'America/New_York', 'exchangeTimezoneShortName': 'EST', 'gmtOffSetMilliseconds': -18000000, 'hasPrePostMarketData': True, 'firstTradeDateMilliseconds': 1013610600000, 'postMarketChangePercent': 0.0, 'postMarketPrice': 24.2, 'postMarketChange': 0.0, 'regularMarketChange': -0.869999, 'regularMarketDayRange': '24.05 - 25.0068', 'fullExchangeName': 'NYSE', 'averageDailyVolume3Month': 7895756, 'fiftyTwoWeekLowChange': 14.250001, 'fiftyTwoWeekLowChangePercent': 1.432161, 'fiftyTwoWeekRange': '9.95 - 64.83', 'fiftyTwoWeekHighChange': -40.63, 'fiftyTwoWeekHighChangePercent': -0.626716, 'fiftyTwoWeekChangePercent': 64.28572, 'dividendDate': 1529971200, 'earningsTimestamp': 1733864709, 'earningsTimestampStart': 1742813940, 'earningsTimestampEnd': 1743163200, 'isEarningsDateEstimate': True, 'epsTrailingTwelveMonths': 0.2, 'epsForward': -0.01, 'epsCurrentYear': 0.07, 'priceEpsCurrentYear': 345.7143, 'fiftyDayAverageChange': -3.7263985, 'fiftyDayAverageChangePercent': -0.13343641, 'twoHundredDayAverageChange': -0.88814926, 'twoHundredDayAverageChangePercent': -0.035401147, 'sourceInterval': 15, 'exchangeDataDelayedBy': 0, 'cryptoTradeable': False, 'displayName': 'GameStop', 'trailingPegRatio': None}

Using the ticker object and the function history extract stock information and save it in a dataframe named gme_data. Set the period parameter to "max" so we get information for the maximum amount of time.

In [21]:
# Extract stock information for GameStop (GME) with maximum time period
gme_data = gme_ticker.history(period="max")

# Display the first few rows of the dataframe
print(gme_data.head())
                               Open      High       Low     Close    Volume  \
Date                                                                          
2002-02-13 00:00:00-05:00  1.620128  1.693350  1.603296  1.691666  76216000   
2002-02-14 00:00:00-05:00  1.712707  1.716074  1.670626  1.683250  11021600   
2002-02-15 00:00:00-05:00  1.683251  1.687459  1.658002  1.674834   8389600   
2002-02-19 00:00:00-05:00  1.666418  1.666418  1.578047  1.607504   7410400   
2002-02-20 00:00:00-05:00  1.615921  1.662210  1.603296  1.662210   6892800   

                           Dividends  Stock Splits  
Date                                                
2002-02-13 00:00:00-05:00        0.0           0.0  
2002-02-14 00:00:00-05:00        0.0           0.0  
2002-02-15 00:00:00-05:00        0.0           0.0  
2002-02-19 00:00:00-05:00        0.0           0.0  
2002-02-20 00:00:00-05:00        0.0           0.0  

Reset the index using the reset_index(inplace=True) function on the gme_data DataFrame and display the first five rows of the gme_data dataframe using the head function. Take a screenshot of the results and code from the beginning of Question 3 to the results below.

In [22]:
# Resetting the index of the gme_data DataFrame
gme_data.reset_index(inplace=True)

# Display the first 5 rows of the gme_data DataFrame
print(gme_data.head())
                       Date      Open      High       Low     Close    Volume  \
0 2002-02-13 00:00:00-05:00  1.620128  1.693350  1.603296  1.691666  76216000   
1 2002-02-14 00:00:00-05:00  1.712707  1.716074  1.670626  1.683250  11021600   
2 2002-02-15 00:00:00-05:00  1.683251  1.687459  1.658002  1.674834   8389600   
3 2002-02-19 00:00:00-05:00  1.666418  1.666418  1.578047  1.607504   7410400   
4 2002-02-20 00:00:00-05:00  1.615921  1.662210  1.603296  1.662210   6892800   

   Dividends  Stock Splits  
0        0.0           0.0  
1        0.0           0.0  
2        0.0           0.0  
3        0.0           0.0  
4        0.0           0.0  

Question 4: Use Webscraping to Extract GME Revenue Data¶

Use the requests library to download the webpage https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/stock.html. Save the text of the response as a variable named html_data_2.

In [23]:
import requests

# URL to download the webpage from
url_2 = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/stock.html"

# Send a GET request to the URL
response_2 = requests.get(url_2)

# Save the text of the response
html_data_2 = response_2.text

# Optionally, print the first 500 characters of html_data_2 to check
print(html_data_2[:500])
<!DOCTYPE html>
<!-- saved from url=(0105)https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/revenue -->
<html class=" js flexbox canvas canvastext webgl no-touch geolocation postmessage websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions fontface g

Parse the html data using beautiful_soup using parser i.e html5lib or html.parser.

In [35]:
from bs4 import BeautifulSoup

# Parse the HTML data using 'html.parser' or 'html5lib'
soup_2 = BeautifulSoup(html_data_2, 'html.parser')  # or 'html5lib'

# Optionally, print the parsed HTML or a part of it
print(soup_2.prettify()[:500])  # Displaying the first 500 characters for review
<!DOCTYPE html>
<!-- saved from url=(0105)https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/revenue -->
<html class="js flexbox canvas canvastext webgl no-touch geolocation postmessage websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions fontface ge

Using BeautifulSoup or the read_html function extract the table with GameStop Revenue and store it into a dataframe named gme_revenue. The dataframe should have columns Date and Revenue. Make sure the comma and dollar sign is removed from the Revenue column.

Note: Use the method similar to what you did in question 2.

Click here if you need help locating the table
    
Below is the code to isolate the table, you will now need to loop through the rows and columns like in the previous lab
    
soup.find_all("tbody")[1]
    
If you want to use the read_html function the table is located at index 1


In [38]:
import requests
from bs4 import BeautifulSoup
import pandas as pd

# Send a GET request to the URL
response_2 = requests.get(url_2)

# Parse the HTML using BeautifulSoup
soup_2 = BeautifulSoup(response_2.text, 'html.parser')

# Find the table with GameStop Revenue
table = soup_2.find_all('table')[0]  # Assuming it's the first table

# Extract table rows
rows = table.find_all('tr')

# Initialize lists for the Date and Revenue columns
dates = []
revenues = []

# Loop through rows and extract Date and Revenue values
for row in rows[1:]:  # Skip the header row
    cols = row.find_all('td')
    if len(cols) > 1:  # Ensure it's a valid row
        dates.append(cols[0].text.strip())
        revenues.append(cols[1].text.strip())

# Create the DataFrame
gme_revenue = pd.DataFrame({
    'Date': dates,
    'Revenue': revenues
})

# Clean the 'Revenue' column by removing commas and dollar signs, and convert to numeric
gme_revenue['Revenue'] = gme_revenue['Revenue'].replace({'\$': '', ',': ''}, regex=True).astype(float)

# Display the first few rows of the cleaned DataFrame
print(gme_revenue.head())
   Date  Revenue
0  2020   6466.0
1  2019   8285.0
2  2018   8547.0
3  2017   7965.0
4  2016   9364.0

Display the last five rows of the gme_revenue dataframe using the tail function. Take a screenshot of the results.

In [39]:
gme_revenue.tail()
Out[39]:
Date Revenue
11 2009 8806.0
12 2008 7094.0
13 2007 5319.0
14 2006 3092.0
15 2005 1843.0

Question 5: Plot Tesla Stock Graph¶

Use the make_graph function to graph the Tesla Stock Data, also provide a title for the graph. Note the graph will only show data upto June 2021.

Hint

You just need to invoke the make_graph function with the required parameter to print the graphs.The structure to call the `make_graph` function is `make_graph(tesla_data, tesla_revenue, 'Tesla')`.

In [49]:
!pip install matplotlib
import matplotlib.pyplot as plt

# Assuming tesla_data is already loaded and has a datetime index

# Convert the index to datetime if it's not already
tesla_data.index = pd.to_datetime(tesla_data.index)

# Filter the data up to June 2021
tesla_data_filtered = tesla_data[tesla_data.index <= '2021-06-30']

# Define the make_graph function
def make_graph(data):
    # Plot the 'Close' stock price data
    plt.plot(data['Close'], label="Tesla Stock Price")
    
    # Set the title of the graph
    plt.title("Tesla Stock Data Up to June 2021")
    
    # Show the labels and the legend
    plt.xlabel('Date')
    plt.ylabel('Stock Price (USD)')
    plt.legend()
    
    # Display the plot
    plt.show()

# Call the function with the filtered data
make_graph(tesla_data_filtered)
Collecting matplotlib
  Downloading matplotlib-3.10.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (11 kB)
Collecting contourpy>=1.0.1 (from matplotlib)
  Downloading contourpy-1.3.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (5.4 kB)
Collecting cycler>=0.10 (from matplotlib)
  Downloading cycler-0.12.1-py3-none-any.whl.metadata (3.8 kB)
Collecting fonttools>=4.22.0 (from matplotlib)
  Downloading fonttools-4.56.0-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (101 kB)
Collecting kiwisolver>=1.3.1 (from matplotlib)
  Downloading kiwisolver-1.4.8-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (6.2 kB)
Requirement already satisfied: numpy>=1.23 in /opt/conda/lib/python3.12/site-packages (from matplotlib) (2.2.3)
Requirement already satisfied: packaging>=20.0 in /opt/conda/lib/python3.12/site-packages (from matplotlib) (24.2)
Collecting pillow>=8 (from matplotlib)
  Downloading pillow-11.1.0-cp312-cp312-manylinux_2_28_x86_64.whl.metadata (9.1 kB)
Collecting pyparsing>=2.3.1 (from matplotlib)
  Downloading pyparsing-3.2.1-py3-none-any.whl.metadata (5.0 kB)
Requirement already satisfied: python-dateutil>=2.7 in /opt/conda/lib/python3.12/site-packages (from matplotlib) (2.9.0.post0)
Requirement already satisfied: six>=1.5 in /opt/conda/lib/python3.12/site-packages (from python-dateutil>=2.7->matplotlib) (1.17.0)
Downloading matplotlib-3.10.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (8.6 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 8.6/8.6 MB 97.5 MB/s eta 0:00:00
Downloading contourpy-1.3.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (323 kB)
Downloading cycler-0.12.1-py3-none-any.whl (8.3 kB)
Downloading fonttools-4.56.0-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.9 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.9/4.9 MB 108.6 MB/s eta 0:00:00
Downloading kiwisolver-1.4.8-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.5 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.5/1.5 MB 50.5 MB/s eta 0:00:00
Downloading pillow-11.1.0-cp312-cp312-manylinux_2_28_x86_64.whl (4.5 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.5/4.5 MB 99.3 MB/s eta 0:00:00
Downloading pyparsing-3.2.1-py3-none-any.whl (107 kB)
Installing collected packages: pyparsing, pillow, kiwisolver, fonttools, cycler, contourpy, matplotlib
Successfully installed contourpy-1.3.1 cycler-0.12.1 fonttools-4.56.0 kiwisolver-1.4.8 matplotlib-3.10.1 pillow-11.1.0 pyparsing-3.2.1
No description has been provided for this image

Question 6: Plot GameStop Stock Graph¶

Use the make_graph function to graph the GameStop Stock Data, also provide a title for the graph. The structure to call the make_graph function is make_graph(gme_data, gme_revenue, 'GameStop'). Note the graph will only show data upto June 2021.

Hint

You just need to invoke the make_graph function with the required parameter to print the graphs.The structure to call the `make_graph` function is `make_graph(gme_data, gme_revenue, 'GameStop')`

In [50]:
import matplotlib.pyplot as plt

# Assuming gme_data and gme_revenue are already loaded DataFrames

# Convert the index to datetime if it's not already
gme_data.index = pd.to_datetime(gme_data.index)

# Filter the data up to June 2021
gme_data_filtered = gme_data[gme_data.index <= '2021-06-30']
gme_revenue_filtered = gme_revenue[gme_revenue['Date'] <= '2021-06-30']

# Define the make_graph function
def make_graph(stock_data, revenue_data, stock_name):
    # Plot the stock price data
    plt.plot(stock_data['Close'], label=f"{stock_name} Stock Price")
    
    # Plot the revenue data (if it's available in 'gme_revenue')
    if not revenue_data.empty:
        plt.plot(revenue_data['Revenue'], label=f"{stock_name} Revenue", linestyle='--')
    
    # Set the title and labels
    plt.title(f"{stock_name} Stock and Revenue Data Up to June 2021")
    plt.xlabel('Date')
    plt.ylabel('Price (USD) / Revenue (in millions)')
    
    # Show the legend
    plt.legend()
    
    # Display the plot
    plt.show()

# Call the function with the filtered data
make_graph(gme_data_filtered, gme_revenue_filtered, 'GameStop')
No description has been provided for this image

About the Authors:

Joseph Santarcangelo has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.

Azim Hirjani

Change Log¶

Date (YYYY-MM-DD) Version Changed By Change Description
2022-02-28 1.2 Lakshmi Holla Changed the URL of GameStop
2020-11-10 1.1 Malika Singla Deleted the Optional part
2020-08-27 1.0 Malika Singla Added lab to GitLab

© IBM Corporation 2020. All rights reserved.